using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BMS.IService;
using BMS.IRepository;
using BMS.DTO;
using AutoMapper;
using AutoMapper.Configuration.Annotations;
using Microsoft.EntityFrameworkCore;
using BMS.Entity.RBAC;

namespace BMS.Service
{
    public class PermissionService : BaseService<PermissionInfo>, IPermissionService
    {
        private readonly IPermissionRepository permissionRepository;
        private readonly IUnitOfWork unitOfWork;
        private readonly IRolePermissionRepository rolePermissionRepository;
        private readonly IRoleUsersRepository roleUsersRepository;
        private readonly IMapper mapper;

        public PermissionService(IPermissionRepository permissionRepository, IUnitOfWork unitOfWork, IRolePermissionRepository rolePermissionRepository, IRoleUsersRepository roleUsersRepository, IMapper mapper) : base(unitOfWork, permissionRepository)
        {
            this.permissionRepository = permissionRepository;
            this.unitOfWork = unitOfWork;
            this.rolePermissionRepository = rolePermissionRepository;
            this.roleUsersRepository = roleUsersRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// //查询权限及该子级权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultDTO<List<PermissionTreeDTO>> GetPermissionInfo(int Pid)
        {
            //查询权限的所有数据
            var list = permissionRepository.GetAll().Result.ToList();
            return new ResultDTO<List<PermissionTreeDTO>>(Recursion(Pid, list));
        }



        /// <summary>
        /// 递归子方法体，用于获取属性的权限数据
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="list">所有权限值</param>
        /// <returns></returns>
        private List<PermissionTreeDTO> Recursion(int id, List<PermissionInfo> list)
        {
            //实例化dto
            List<PermissionTreeDTO> dto = new List<PermissionTreeDTO>();
            //根据父级id查询数据list1
            var list1 = list.Where(x => x.Pid == id && !x.IsDeleted).OrderByDescending(m => m.OrderSort).ToList();
            //循环数据list1判断是否存在子级
            foreach (var item in list1)
            {
                var t = Recursion(item.Id, list);
                dto.Add(new PermissionTreeDTO
                {
                    Id = item.Id,
                    Pid = item.Pid,
                    ApiAction = item.ApiAction,
                    Category = item.Category,
                    Describe = item.Describe,
                    Icon = item.Icon,
                    Identifier = item.Identifier,
                    Name = item.Name,
                    OrderSort = item.OrderSort,
                    Status = item.Status,
                    UrlPath = item.UrlPath,
                    children = Recursion(item.Id, list)
                }) ;
            }
            return dto.Count()>0?dto:null;
        
        }

        /// <summary>
        /// 权限的倒序显示+分页+查询
        /// </summary>
        /// <param name="Pagesize"></param>
        /// <param name="Pageindex"></param>
        /// <param name="PermissionInfoName"></param>
        /// <returns></returns>
        public async Task<PageDTO<PermissionInfoDTO>> ReverseOrderShow(int Pagesize, int Pageindex, string PermissionInfoName="")
        {
            var data = from a in await permissionRepository.GetAll()
                       select new PermissionInfoDTO
                       {
                           Pid = a.Pid,
                           Name = a.Name,
                           Status = a.Status,
                           Action = a.ApiAction,
                       };
                if(!string.IsNullOrEmpty("PermissionInfoName"))
            {
                data = data.Where(x => x.Name.Contains(PermissionInfoName));
            }
            return new PageDTO<PermissionInfoDTO>
            {
                recordCount = data.Count(),
                plist = data.OrderByDescending(a => a.Pid).Skip((Pageindex - 1) * Pagesize).Take(Pagesize)
            };
        }

        /// <summary>
        /// 权限的显示+分页+查询
        /// </summary>
        /// <param name="PermissionInfoName"></param>
        /// <param name="Pagesize"></param>
        /// <param name="Pageindex"></param>
        /// <returns></returns>
        public async Task<PageDTO<PermissionInfoDTO>> PermissionInfoShow(int Pagesize, int Pageindex, string PermissionInfoName = "")
        {
            var data = from a in await permissionRepository.GetAll()
                      
                       select new PermissionInfoDTO
                       {
                           Pid= a.Pid,
                           Name=a.Name,
                           Action=a.ApiAction,
                           Status=a.Status,
                       };
            //权限名称模糊查询
            if (!string.IsNullOrEmpty(PermissionInfoName))
            {
                data = data.Where(a => a.Name.Contains(PermissionInfoName));
            }
            return new PageDTO<PermissionInfoDTO>
            {
                recordCount = data.Count(),
                plist = data.OrderBy(a => a.Pid).Skip((Pageindex - 1) * Pagesize).Take(Pagesize)
            };
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> PermissionDel(int id)
        {
            //查询逻辑删除的权限
            var data = permissionRepository.GetAll().Result.Where(x => x.Id == id && x.IsDeleted==false).FirstOrDefault();
            try
            {
                //判断是否为空，判断修改权限表
                if (data == null)
                {
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.ENTITYNULL,
                        Message = "删除失败",
                        Data = "权限不存在"
                    };
                }
                data.IsDeleted = true;
                await permissionRepository.Update(data);
                //提交
                await unitOfWork.SaveChanges();
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "删除成功",
                    Data = "权限：" + data.Name + "已删除",
                };
            }
            catch (Exception)
            {
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "删除失败",
                    Data = "权限：" + data.Name + "未删除",
                };
                  
               
            }
          


        }

        /// <summary>
        /// 权限添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> PermissionAdd(PermissionAddDto dto)
        {
            //开启事务
            var tran = unitOfWork.GetDbContext().Database.BeginTransaction();
            try
            {
                //转为实体类型
                var permission = mapper.Map<PermissionInfo>(dto);
                //添加权限信息
                await permissionRepository.Insert(permission);
                int h= await unitOfWork.SaveChanges();
                //提交事务
                tran.Commit();
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "添加成功",
                    Data = "权限名：" + dto.Name + "添加成功",
                };
            }
            catch (Exception)
            {
                //出错回滚事务
                tran.Rollback();
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "添加失败",
                    Data = "",
                };
               
            }
          

        }

        /// <summary>
        /// 权限修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> PermissionInfoDTO(PermissionAddDto dto)
        {
            try
            {
                //判断实体类是否存在
                var permission =await (await permissionRepository.GetAll()).Where(m => m.Id == dto.Id).FirstOrDefaultAsync();

                //判断是否为空
                if (permission == null)
                {
                    return new ResultDTO<string>("-1",Enum.ResultStatusCode.ENTITYNULL,"实体信息为空！！！");
                }

                //转为实体类型
                permission = mapper.Map<PermissionInfo>(dto);
                //修改权限信息
                await permissionRepository.Update(permission);
                int h= await unitOfWork.SaveChanges();
                return new ResultDTO<string>
                {
                    Code =Enum.ResultStatusCode.SUCCESS,
                    Message = "权限：" + dto.Name + "修改成功",
                    Data = "修改成功",
                };
            }
            catch (Exception ex)
            {
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.HANDLEFAIL,
                    Message = "权限：" + dto.Name + "修改失败",
                    Data = ex.Message,
                };
              
            }
        }

        /// <summary>
        /// 真.权限删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> Delete(int id)
        {
            try
            {
                //查询删除的权限
                var data = permissionRepository.GetAll().Result.Where(x => x.Id == id).FirstOrDefault();
                var delete = permissionRepository.Delete(data);
                await unitOfWork.SaveChanges();
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "真.删除成功",
                    Data = "",
                };
            }
            catch (Exception)
            {
                return new ResultDTO<string>
                {
                    Code = Enum.ResultStatusCode.SUCCESS,
                    Message = "真.删除失败",
                    Data = "",
                };
            }
         
           
        }

        /// <summary>
        /// 获取菜单权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public async Task<ResultDTO<List<MenuDTO>>> GetMenus(int userId)
        {
            //获取该用户的角色ID值
            var roles = (await roleUsersRepository.GetAll()).Where(m => m.UserId == userId).Select(m => m.RoleId).ToList();

            List<PermissionInfo> list = new List<PermissionInfo>();

            //循环获取所有权限信息
            foreach (var role in roles)
            {
                //获取一个角色中所有的权限信息
                list.AddRange(await GetRoleToPermission((int)role));
            }

            //对权限信息进行去重
            list = list.Distinct().ToList();
            var temp = new List<PermissionInfo>();

            //获取这些权限信息的父级信息
            foreach (var item in list)
            {
                var m = await permissionRepository.GetParentId(item.Pid);
                if (m != null)
                {
                    temp.AddRange(m);
                }
            }
            temp = temp.DistinctBy(m=>m.Id).ToList();
            list.AddRange(temp);
            list= list.OrderByDescending(m => m.OrderSort).ToList();

            //获取对权限进行菜单来的层级显示，使用递归
            List<MenuDTO> menu = RecursionToMenu(0, list);

            return new ResultDTO<List<MenuDTO>>(menu);
        }

        /// <summary>
        /// 获取一个角色中所有的权限信息
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        private async Task<List<PermissionInfo>> GetRoleToPermission(int roleId)
        {
            //获取该角色的所有权限id
            var permissionIds = (await rolePermissionRepository.GetAll()).Where(m => m.RoleId == roleId).Select(m => m.PermissionId).ToList();
            var permissionData = (await permissionRepository.GetAll()).Where(m=>(int)m.Category==20||(int)m.Category==10).ToList();

            //根据ID将这些信息变为权限值信息
            var list = new List<PermissionInfo>();

            foreach (var item in permissionIds)
            {
                var m = permissionData.Where(m => m.Id == item).ToList().FirstOrDefault();
                if (m != null)
                {
                    list.Add(m);
                }
            }

            return list;
        }
        /// <summary>
        /// 获取对权限进行菜单来的层级显示，使用递归
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="list">所有权限值</param>
        /// <returns></returns>
        private List<MenuDTO> RecursionToMenu(int id, List<PermissionInfo> list)
        {
            //实例化dto
            List<MenuDTO> dto = new List<MenuDTO>();
            //根据父级id查询数据list1
            var list1 = list.Where(x => x.Pid == id).ToList();
            //循环数据list1判断是否存在子级
            foreach (var item in list1)
            {
                ///var t = RecursionToMenu(item.Id, list);
                dto.Add(new MenuDTO
                {
                    icon = item.Icon,
                    index = item.UrlPath,
                    title = item.Name,
                    subs = RecursionToMenu(item.Id, list)
                });
            }
            return dto.Count()>0?dto:null;

        }



        /// <summary>
        /// 权限的批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> PermissionsSoftDelAll(string idList)
        {
            string[] ids = idList.Split(',');

            var listt = await permissionRepository.GetAll();

            //循环判断选中权限是否被删除
            foreach (var id in ids)
            {

                var list = listt.Where(m => m.Id == Convert.ToInt32(id) && m.IsDeleted == false).FirstOrDefault();
                if (list == default)
                {
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.ENTITYNULL,
                        Message = "存在未查找到的权限",
                        Data = "权限编号：" + id + "的权限不存在"
                    };
                }
              

            }

            //开启事务
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //批量修改
                    foreach (var id in ids)
                    {
                        var role = (await permissionRepository.GetAll()).Where(m => m.Id == Convert.ToInt32(id)).FirstOrDefault();
                        role.IsDeleted = true;
                        role.UpdateTime = DateTime.Now;
                        await permissionRepository.Update(role);
                    }

                    //提交数据
                    await unitOfWork.SaveChanges();

                    //提交事务
                    tran.Commit();

                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.SUCCESS,
                        Message = "删除成功",
                        Data = "权限已批量删除"
                    };
                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Rollback();
                    return new ResultDTO<string>
                    {
                        Code = Enum.ResultStatusCode.HANDLEFAIL,
                        Message = "删除失败",
                        Data = null
                    };
                }
            }
        }



       


    }
}
